/*
 * Project: com.common.framework.util
 *
 * File Created at 2019-10-20
 *
 * Copyright 2019 CMCC Corporation Limited.
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of
 * ZYHY Company. ("Confidential Information").  You shall not
 * disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license.
 */
package com.common.framework.util;

import javax.validation.constraints.NotEmpty;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * @author jianghucoding
 * @date 2019-10-20
 */
public class DateUtil {

    /**
     * 使用 SimpleDateFormat 来避免每个方法创建对象的低效问题
     * 和不正确的使用可能存在的线程安全问题
     */
    private final static ThreadLocal<SimpleDateFormat> DF = new ThreadLocal<>();

    private DateUtil() { }

    public static Date addHour(Date date, int hour) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.HOUR, hour);
        return calendar.getTime();
    }

    public static String formatToString(Date date, String pattern) {
        return getSimpleDateFormat(pattern).format(date);
    }

    private static SimpleDateFormat getSimpleDateFormat(@NotEmpty String datePattern) {
        SimpleDateFormat simpleDateFormat = DF.get();
        if (simpleDateFormat != null && datePattern.equals(simpleDateFormat.toPattern())) {
            return simpleDateFormat;
        }
        simpleDateFormat = new SimpleDateFormat(datePattern);
        DF.set(simpleDateFormat);
        return simpleDateFormat;
    }
}
